package com.ug.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ug.common.id.SnowFlakeFactory;
import com.ug.system.entity.SysRoleUser;
import com.ug.system.mapper.SysRoleUserMapper;
import com.ug.system.service.SysRoleUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author LY
 * @create 2024/7/17 9:17
 * @Description 用户角色服务实现层
 */
@Service
@RequiredArgsConstructor
public class SysRoleUserServiceImpl extends ServiceImpl<SysRoleUserMapper, SysRoleUser> implements SysRoleUserService {

    @Override
    public List<SysRoleUser> getRoleUserByRoleId(Long roleId) {
        LambdaQueryWrapper<SysRoleUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysRoleUser::getRoleId, roleId);
        return baseMapper.selectList(wrapper);
    }

    @Override
    public void edit(Long userId, List<String> roleIds) {
        //  首先清空该用户所有角色
        LambdaQueryWrapper<SysRoleUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysRoleUser::getUserId, userId);
        baseMapper.delete(wrapper);
        //  然后将用户与角色绑定
        //TODO 可优化成批量操作插入
        roleIds.forEach(role -> {
            SysRoleUser roleUser = new SysRoleUser();
            roleUser.setId(SnowFlakeFactory.getSnowFlakeFromCache().nextId());
            roleUser.setUserId(userId);
            roleUser.setRoleId(Long.parseLong(role));
            baseMapper.insert(roleUser);
        });
    }

    @Override
    public List<SysRoleUser> getRoleUserByUserId(Long userId) {
        LambdaQueryWrapper<SysRoleUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysRoleUser::getUserId, userId);
        return baseMapper.selectList(wrapper);
    }

    @Override
    public void deleteByUserId(String userId) {
        LambdaQueryWrapper<SysRoleUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysRoleUser::getUserId, userId);
        baseMapper.delete(wrapper);
    }
}
